// Author: wsfuyibing <682805@qq.com>
// Date: 2025-07-03

package prepay_session

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/log"
	"server/app/lib/order/operations"
	"sync"
)

var (
	once     = new(sync.Once)
	operator *Operator
)

// Operator
// 发起试算.
type Operator struct {
	operations.Operations
}

// New
// 操作单例.
func New() *Operator { return operator }

// Run
// 执行试算.
func (o *Operator) Run(ctx context.Context, sess *db.Session, entity *operations.SessionEntity) (pre *operations.Prepay, err error) {
	// 1. 开始试算.
	log.Infofc(ctx, `[lib][order] 开始试算`)

	// 2. 监听结束.
	defer func() {
		if err != nil {
			log.Warnfc(ctx, `[lib][order] 试算失败: %v`, err)
		} else {
			log.Infofc(ctx, `[lib][order] 试算结束: 自付="%v", 总价="%v", 会员抵扣="%v", 余额抵扣="%v", 优惠券抵扣="%v", 总抵扣="%v"`,
				pre.PayAmount,
				pre.TotalAmount,
				pre.MemberAmount,
				pre.BalanceAmount,
				pre.CouponAmount,
				pre.TotalDiscount,
			)
		}
	}()

	// 3. 试算过程.
	if err = o.LoadEntityForSession(ctx, sess, entity); err == nil {
		if pre, err = o.CheckSessionEntity(ctx, entity); err == nil {
			pre.ResetPayAmount().End(&entity.Entity)
		}
	}
	return
}

// +---------------------------------------------------------------------------+
// | Initialize a singleton instance.                                          |
// +---------------------------------------------------------------------------+

func init() {
	once.Do(func() {
		operator = &Operator{}
	})
}
